<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\wechat\controller;

use app\wechat\service\FansService;
use app\wechat\service\TagsService;
use controller\BasicAdmin;
use service\LogService;
use service\ToolsService;
use service\WechatService;
use think\Db;

/**
 * 微信粉丝管理
 * Class Fans
 * @package app\wechat\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/03/27 14:43
 */
class Fans extends BasicAdmin
{

    /**
     * 定义当前默认数据表
     * @var string
     */
    public $table = 'store_member';

    public function userlevel(){
        $userlist = Db::name('store_member')->select();
        foreach($userlist as $val){
            if ($val['integral'] >= 5 && $val['integral'] < 10){
                Db::name('store_member')->where('id',$val['id'])->update(['level' => 1]);
            }elseif ($val['integral'] >= 10 && $val['integral'] < 15){
                Db::name('store_member')->where('id',$val['id'])->update(['level' => 2]);
            }elseif ($val['integral'] >= 15 && $val['integral'] < 20){
                Db::name('store_member')->where('id',$val['id'])->update(['level' => 3]);
                echo 3;
            }elseif ($val['integral'] >= 20){
                Db::name('store_member')->where('id',$val['id'])->update(['level' => 4]);
                echo 4;
            }
        }
    }

    /**
     * 显示粉丝列表
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function index()
    {
        $this->title = '用户列表';
        $get = $this->request->get();

        $db = Db::table('store_member');
        if($this->user['id'] != 10000) {
            if (strlen($this->shopUnderUsers) > 0 || empty($this->shopUnderUsers)) {
                $db->where('id', 'in', $this->shopUnderUsers);
            }
        }
        $shoplist = Db::name('store_shops')->select();
        $this->assign('shop',$shoplist);

        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }


        if (isset($get['nickname']) && $get['nickname'] !== '') {
            $db->where('nickname', 'like',"%{$get['nickname']}%");
        }
        if (isset($get['phone']) && $get['phone'] !== '') {
            $db->where('phone', 'like',"%{$get['phone']}%");
        }
        if (isset($get['member_level']) && $get['member_level'] !== '') {
            $db->where('member_level', '=',$get['member_level']);
        }
        if (isset($get['carid']) && $get['carid'] !== '') {
            $db->where('carid', '=',$get['carid']);
        }

        if (isset($get['shop_id']) && $get['shop_id'] !== ''){
            $db->where('shop_id     ','=',$get['shop_id']);
        }

        return parent::_list($db->order('create_at desc'));
    }

    public function _index_data_filter( &$data )
    {
        foreach($data as &$v) {
            $v['member_level_info'] = Db::name('sys_level')->where(['id' => $v['member_level']])->value('title');
            $v['team_num'] = Db::query("SELECT count(*) as sub_person_count  FROM `store_member` WHERE FIND_IN_SET({$v['id']},all_leader)")[0]['sub_person_count'];
            $v['company'] = Db::name('store_shops')->where(['id'=>$v['shop_id']])->find();
        }
        $sys_level = Db::name('sys_level')->select();
        $this->assign('sys_level',$sys_level);
    }


    public function integral()
    {
        $this->title = '资金明细';
        $get = $this->request->get();
        $db = Db::name("bags_log");
        $where = array();

        if($this->user['id'] != 10000) {
            if (strlen($this->shopUnderUsers) > 0 || empty($this->shopUnderUsers)) {
                $db->where('uid', 'in', $this->shopUnderUsers);
            }
        }
        if (isset($get['orderid']) && $get['orderid'] != '') {
            $where['orderid'] = $get['orderid'];
            $db->where($where);
        }

        if (isset($get['member_id']) && $get['member_id'] != '') {
            $where['uid'] = $get['member_id'] ;
            $db->where($where);
        }

        if (isset($get['type']) && $get['type'] != '') {
            $where['type'] = $get['type'];
            $db->where($where);
        }

        if (isset($get['extends']) && $get['extends'] != '') {
            $where['extends'] = $get['extends'];
            $db->where($where);
        }
        if (isset($get['date']) && $get['date'] != '') {
            $date = $get['date'];
            list($start, $end) = explode(' - ', $date);
            $db->where('create_time', 'between', [strtotime($start), strtotime($end)]);
        }
        if (isset($get['field']) && $get['field'] != '') {
            if ($get['field'] == 'phone') {
                $get['name'] && $where['uid'] = Db::name('store_member')->where(array('phone' => $get['name']))->value('id');
            } elseif($get['field'] == 'username') {
                $get['name'] && $where['uid'] = Db::name('store_member')->where(array('nickname' => $get['name']))->value('id');
            }else{
                $where[$get['field']] = $get['name'];
            }

            $db->where($where);
        }
        $db->order('create_time desc,id desc');
        return parent::_list($db);
    }


    /**
     * 设置黑名单
     */
    public function backadd()
    {

        try {
            $is_disable = Db::name($this->table)->where('id', input('param.id'))->value('is_disable');
            $is_disable = $is_disable == 1 ? -1 : 1;
            Db::name($this->table)->where('id', input('param.id'))->setField('is_disable', $is_disable);
        } catch (\Exception $e) {
            $this->error("操作失败，请稍候再试！");
        }
        $this->success('操作成功！', '');
    }

    /**
     * 标签选择
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tagset()
    {
        $tags = $this->request->post('tags', '');
        $fans_id = $this->request->post('fans_id', '');
        $fans = Db::name('WechatFans')->where(['id' => $fans_id])->find();
        empty($fans) && $this->error('需要操作的数据不存在!');
        try {
            $wechat = WechatService::WeChatTags();
            foreach (explode(',', $fans['tagid_list']) as $tagid) {
                is_numeric($tagid) && $wechat->batchUntagging([$fans['openid']], $tagid);
            }
            foreach (explode(',', $tags) as $tagid) {
                is_numeric($tagid) && $wechat->batchTagging([$fans['openid']], $tagid);
            }
            Db::name('WechatFans')->where(['id' => $fans_id])->setField('tagid_list', $tags);
        } catch (\Exception $e) {
            $this->error('粉丝标签设置失败, 请稍候再试!');
        }
        $this->success('粉丝标签成功!', '');
    }

    /**
     * 给粉丝增加标签
     */
    public function tagadd()
    {
        $tagid = $this->request->post('tag_id', 0);
        empty($tagid) && $this->error('没有可能操作的标签ID');
        try {
            $openids = $this->_getActionOpenids();
            WechatService::WeChatTags()->batchTagging($openids, $tagid);
        } catch (\Exception $e) {
            $this->error("设置粉丝标签失败, 请稍候再试! " . $e->getMessage());
        }
        $this->success('设置粉丝标签成功!', '');
    }

    /**
     * 移除粉丝标签
     */
    public function tagdel()
    {
        $tagid = $this->request->post('tag_id', 0);
        empty($tagid) && $this->error('没有可能操作的标签ID');
        try {
            $openids = $this->_getActionOpenids();
            WechatService::WeChatTags()->batchUntagging($openids, $tagid);
        } catch (\Exception $e) {
            $this->error("删除粉丝标签失败, 请稍候再试! ");
        }
        $this->success('删除粉丝标签成功!', '');
    }

    /**
     * 获取当前操作用户openid数组
     * @return array
     */
    private function _getActionOpenids()
    {
        $ids = $this->request->post('id', '');
        empty($ids) && $this->error('没有需要操作的数据!');
        $openids = Db::name($this->table)->whereIn('id', explode(',', $ids))->column('openid');
        empty($openids) && $this->error('没有需要操作的数据!');
        return $openids;
    }

    /**
     * 同步粉丝列表
     */
    public function sync()
    {
        try {
            Db::name($this->table)->where('1=1')->delete();
            [FansService::sync(), TagsService::sync()];
            LogService::write('微信管理', '同步全部微信粉丝成功');
        } catch (\Exception $e) {
            $this->error('同步粉丝记录失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('同步获取所有粉丝成功！', '');
    }


    public function user_add()
    {
        if (!$this->request->isPost()) {
            $sys_level = Db::name('sys_level')->select();
            $member_id = input('param.member_id',0);

            if($member_id){
                $info = Db::name('store_member')->where(['id'=>$member_id])->find();
                $info['first_leader'] = Db::name('store_member')->where(['id'=>$info['first_leader']])->value('phone');
                $this->assign('info',$info);
            }
            $this->assign('sys_level', $sys_level);
        } else {
            $data = $this->request->post();
            $parentid = 0;

            if (!empty($data['parent_phone'])) {
                $parentid = Db::name('store_member')->where(['phone' => $data['parent_phone']])->value('id');
                !$parentid && $this->error('上级用户不存在呢');
            }
            if(!isset($data['id'])){
                $user_flag = Db::name('store_member')->where(['phone' => $data['phone']])->find();
                $user_flag && $this->error('账号已经存在了');
            }
            unset($data['parent_phone']);
            if(isset($data['id'])){
                if(!empty($data['password'])){
                    if(strlen($data['password']) == '32'){
                        //不修改
                        unset($data['password']);
                    }else{
                        $data['password'] = md5($data['password']);
                    }
                }
                if(!empty($data['paypassword'])){
                    if(strlen($data['paypassword']) == '32'){
                        //不修改
                        unset($data['paypassword']);
                    }else{
                        $data['paypassword'] = md5($data['paypassword']);
                    }
                }
                $result = Db::name('store_member')->where(['id'=>$data['id']])->update($data);
            }else{
                $data['password'] = md5($data['password']);
                $result = Db::name('store_member')->insertGetId($data);
            }
            if ($result !== FALSE) {
                \think\facade\Hook::listen('AssocUserParent', ['user_id' => $result, 'parent_id' => $parentid]);
                $this->success('操作成功','');
            } else {
                $this->error('操作失败','');
            }
        }
        return view();
    }

    public function user_balance()
    {
        if($this->request->post()){
            $data = $this->request->post();
            if($data['member_id']){
                $userInfo = Db::name('store_member')->where('id',$data['member_id'])->find();

                $content_str = '';
                if($data['recharge_type'] ==1){
                    if($data['integral'] > $userInfo['integral']) $this->error('用户积分不足');
                    $content_str = "后台减少用户:{$data['member_id']},积分:{$data['integral']}";
                    $data['integral'] = '-'.$data['integral'];
                }else{
                    $content_str = "后台增加用户:{$data['member_id']},积分:{$data['integral']}";
                    $data['integral'] = $data['integral'];
                }
                Db::startTrans();
                $res = mlog($data['member_id'],'integral',$data['integral'],$content_str,'20');
                if(check_arr($res)){
                    Db::commit();
                    return $this->success('操作成功','');
                }else{
                    Db::rollback();
                    return $this->error('操作失败');
                }
            }else{
                return $this->error('账户不存在！');
            }
        }
        return view();
    }
}
